import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores'
//createWebHistory括号中的参数是路由的基准路径，可以在vite.config.js中配置
//import.meta.env.BASE_URL是vite的环境变量，默认值是/
//如果在vite.config.js中配置了base: '/big-event/',那么import.meta.env.BASE_URL就是/big-event/
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path:'/login',
      component:()=>import('@/views/login/LoginPage.vue')
    },
    {
      path:'/',
      component:()=>import('@/views/layout/LayoutContainer.vue'),
      redirect:'/article/manage',
      children:[
        {
          path:'/article/manage',component:()=>import('@/views/article/ArticleManage.vue')
        },
        {
          path:'/article/channel',component:()=>import('@/views/article/ArticleChannel.vue')
        },
        {
          path:'/user/profile',component:()=>import('@/views/user/UserProfile.vue')
        },
        {
          path:'/user/password',component:()=>import('@/views/user/UserPassword.vue')
        },
        {
          path:'/user/avatar',component:()=>import('@/views/user/UserAvatar.vue')
        }
      ]
    },
  ],
})

 router.beforeEach(async (to) => {
const userStore = useUserStore()
   if (
     // 检查用户是否已登录
     !userStore.token &&
     // ❗️ 避免无限重定向
     to.path !== '/login'
   ) {
     // 将用户重定向到登录页面
     return { path: '/login' }
   }
   if (
     // 检查用户是否已登录
     userStore.token &&
     // ❗️ 避免无限重定向
     to.path === '/login'
   ) {
     // 将用户重定向到登录页面
     return { path: '/article/manage' }
   }
 })
export default router
